// 初始化中奖历史记录
let history = JSON.parse(localStorage.getItem('lotteryHistory') || '[]');

function updateHistoryDisplay() {
  const historyList = document.getElementById('historyList');
  historyList.innerHTML = history.map(entry => 
    `<li>
      <span>${entry.winner}</span>
      <span>${new Date(entry.timestamp).toLocaleString()}</span>
    </li>`
  ).join('');
}

function startLottery() {
  const textarea = document.getElementById('participants');
  const resultDiv = document.getElementById('result');
  
  // 解析参与者名单
  const participants = textarea.value
    .split('\n')
    .map(name => name.trim())
    .filter(name => name.length > 0);

  if (participants.length === 0) {
    resultDiv.innerHTML = '⚠️ 请输入参与者名单';
    return;
  }

  // 洗牌算法实现公平随机
  const shuffled = [...participants].sort(() => Math.random() - 0.5);
  
  // 添加动画效果
  let count = 0;
  const animation = setInterval(() => {
    resultDiv.innerHTML = shuffled[count % shuffled.length];
    count++;
    if (count > 15) clearInterval(animation);
  }, 50);

  // 最终结果显示
  setTimeout(() => {
    const winner = shuffled[Math.floor(Math.random() * shuffled.length)];
    resultDiv.innerHTML = `🎉 中奖者：${winner}`;
    
    // 记录历史
    history.unshift({
      winner,
      timestamp: new Date().toISOString()
    });
    localStorage.setItem('lotteryHistory', JSON.stringify(history));
    updateHistoryDisplay();
  }, 800);
}

// 初始化显示历史记录
updateHistoryDisplay();